package de.idgard.android.addon.ui.dialogs;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.PictureDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import de.idgard.android.R;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.AddonUIManager;
import de.idgard.android.addon.ui.services.LayoutAdjustmentService;
import de.idgard.android.addon.ui.services.PropertiesService;
import de.idgard.android.addon.ui.services.ZircoToIDGardAPI;
import de.idgard.android.addon.ui.services.impl.UIServiceRegistry;

/**
 * @author pratik popat: Browser's Quick tab layout.
 * 
 */
public class TabDialog extends Activity implements OnClickListener {

	private ZircoToIDGardAPI getZircoToIDGardAPI() {
		return GlobalServiceRegistry.instance().getZircoToIDGardAPI();
	}

	private final int CLOSE_ID = 1000;
	private final int LL_TAB_ITEM_ID = 2000;
	private final int THUMB_ID = 3000;

	private LinearLayout ll_tab;

	private ImageButton ibAddTab, ibCloseWindow, ibPreviousTab, ibNextTab;

	private HorizontalScrollView hsv_tab_view;

	/* Tab items array */
	ArrayList<TabItem> arrTabItem = new ArrayList<TabDialog.TabItem>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.browser_tab_dialog);

		hsv_tab_view = (HorizontalScrollView) findViewById(R.id.hsv_tab);
		ll_tab = (LinearLayout) findViewById(R.id.ll_tab_dialog);
		ibCloseWindow = (ImageButton) findViewById(R.id.ib_close_tab_window);
		ibAddTab = (ImageButton) findViewById(R.id.ib_add_tab);
		ibPreviousTab = (ImageButton) findViewById(R.id.ib_previous_tab);
		ibNextTab = (ImageButton) findViewById(R.id.ib_next_tab);

		ibPreviousTab.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				hsv_tab_view.pageScroll(HorizontalScrollView.FOCUS_LEFT);
				hsv_tab_view.refreshDrawableState();
			}
		});

		ibNextTab.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				hsv_tab_view.pageScroll(HorizontalScrollView.FOCUS_RIGHT);
				hsv_tab_view.refreshDrawableState();
			}
		});

		ibAddTab.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				addNewTab();
				finish();
			}
		});

		ibCloseWindow.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		buildTabGui();
	}

	private void addNewTab() {
		ViewFlipper vf = getZircoToIDGardAPI().getViewFlipper();
		getZircoToIDGardAPI().addTab(true, vf.getDisplayedChild());
		getZircoToIDGardAPI().startToolbarsHideRunnable();
	}

	private PropertiesService getPropertiesService() {
		return UIServiceRegistry.instance().getPropertiesService();
	}

	private LayoutAdjustmentService getlayAdjustmentService() {
		return UIServiceRegistry.instance().getlayouAdjustmentService();
	}

	/**
	 * @param obj
	 * @param action
	 */
	private void invokeOnView(WebView obj, String action) {
		try {
			WebView.class.getMethod(action).invoke(obj, null);
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	private void buildTabGui() {

		int index = 0;

		List<WebView> wvs = getZircoToIDGardAPI().getContainersWebViews();

		ll_tab.removeAllViews();

		if (!wvs.isEmpty()) {
			for (WebView view : wvs) {
				invokeOnView(view, "onPause");
				synchronized (getZircoToIDGardAPI().getViewFlipper()) {
					addTabItems(view, index);
					index++;
				}
			}
			drawTabItemBorderAndSetTitle();
		}
	}

	private int getCurrentTabIndex() {
		ViewFlipper vf = getZircoToIDGardAPI().getViewFlipper();
		return vf.getDisplayedChild();
	}

	private void addTabItems(WebView view, int index) {
		TabItem tabitem = new TabItem();
		Bitmap thumbnail = null;

		LinearLayout ll_tab_item = new LinearLayout(getApplicationContext());
		ll_tab_item.setOrientation(LinearLayout.VERTICAL);
		ll_tab_item.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
		ll_tab_item.setId(LL_TAB_ITEM_ID + index);

		ImageView iv_tab_thumb = new ImageView(getApplicationContext());
		iv_tab_thumb.setOnClickListener(this);
		iv_tab_thumb.setId(THUMB_ID + index);
		iv_tab_thumb.setPadding(2, 2, 2, 2);

		thumbnail = getWebViewThumbnail(view);
		iv_tab_thumb.setImageBitmap(thumbnail);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(10, 0, 10, 10);
		iv_tab_thumb.setLayoutParams(lp);

		tabitem.setIv_thumb(iv_tab_thumb);

		ImageView iv_close = new ImageView(getApplicationContext());
		iv_close.setImageDrawable(AddonUIManager.getInstance().getContainerActivity().getResources().getDrawable(R.drawable.btn_tab_delete));
		iv_close.setId(CLOSE_ID + index);
		iv_close.setOnClickListener(this);

		tabitem.setTitle(view.getTitle());

		TextView tv_tabTitle = new TextView(getApplicationContext());
		tv_tabTitle.setTextColor(Color.WHITE);
		tv_tabTitle.setGravity(Gravity.CENTER);
		tv_tabTitle.setTextSize(20);
		tabitem.setTvTitle(tv_tabTitle);

		ll_tab_item.addView(iv_close);
		ll_tab_item.addView(iv_tab_thumb);
		ll_tab_item.addView(tv_tabTitle);

		ll_tab.addView(ll_tab_item);
		arrTabItem.add(tabitem);
	}

	private void drawTabItemBorderAndSetTitle() {
		Log.i("arr_thumb:", "" + arrTabItem);

		for (int i = 0; i < arrTabItem.size(); i++) {

			ImageView thumb = arrTabItem.get(i).getIv_thumb();

			if (i == getCurrentTabIndex())
				thumb.setBackgroundColor(getPropertiesService().getColor(R.color.tab_border_red));
			else
				thumb.setBackgroundColor(getPropertiesService().getColor(R.color.tab_border_grey));

			thumb.invalidate();

			String title = arrTabItem.get(i).getTitle();
			TextView tvTitle = arrTabItem.get(i).getTvTitle();
			tvTitle.setText(formatTitle(title, i));
			tvTitle.invalidate();
		}
		ll_tab.invalidate();
	}

	private String formatTitle(String title, int index) {

		String tabTitle;
		tabTitle = getPropertiesService().getString(R.string.tab) + " " + (index + 1) + getPropertiesService().getString(R.string.col) + " ";
		if (title != null) {
			if (title.length() > 10) {
				title = title.substring(0, 10) + getPropertiesService().getString(R.string.dots);
			}
			tabTitle += title;
		}

		return tabTitle;
	}

	private Bitmap getWebViewThumbnail(WebView view) {

		Bitmap bmp = null;
		try {
			PictureDrawable pic = new PictureDrawable(view.capturePicture());
			bmp = resizeBmpToAdjustScreen(pictureDrawable2Bitmap(pic), 25);
		} catch (Exception e) {
			bmp = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.ic_web_page);
			bmp = resizeBmpToAdjustScreen(bmp, 18);
			e.printStackTrace();
		}

		return bmp;
	}

	private Bitmap resizeBmpToAdjustScreen(Bitmap bmp, int prc) {

		int s_width = getlayAdjustmentService().getScreenWidth();
		int s_height = getlayAdjustmentService().getScreenHeight();

		int width = s_width * prc / 100;
		int height = s_height * prc / 100;

		return Bitmap.createScaledBitmap(bmp, width, height, false);
	}

	private Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable) {
		Bitmap bitmap = null;
		try {
			bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
			Canvas canvas = new Canvas(bitmap);
			canvas.drawPicture(pictureDrawable.getPicture());
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	@Override
	public void onClick(View v) {
		Log.i(this.getClass().getName(), "View Id:" + v.getId());

		if (v.getId() >= CLOSE_ID && v.getId() < THUMB_ID) {
			removeTab(v.getId() - CLOSE_ID);
			setCurrentWebView();
			return;
		}
		if (v.getId() >= THUMB_ID) {
			getZircoToIDGardAPI().getViewFlipper().setDisplayedChild(v.getId() - THUMB_ID);
			setCurrentWebView();
			getZircoToIDGardAPI().updateBrowserUI();
			this.finish();
		}

	}

	private void removeTab(int vIndex) {

		if (getZircoToIDGardAPI().getViewFlipper().getChildCount() > 1) {
			/* move to selected tab */
			getZircoToIDGardAPI().getViewFlipper().setDisplayedChild(vIndex);
			/* removes selected tab */
			getZircoToIDGardAPI().removeCurrentTab();
			try {
				arrTabItem.remove(vIndex);
			} catch (Exception e) {
				e.printStackTrace();
			}
			refreshTabDialog(vIndex);

		}
	}

	private void setCurrentWebView() {
		WebView wv = getZircoToIDGardAPI().getContainersWebViews().get(getZircoToIDGardAPI().getViewFlipper().getDisplayedChild());
		getZircoToIDGardAPI().setCurrentWebView(wv);
	}

	private void refreshTabDialog(int vIndex) {
		try {
			ll_tab.removeViewAt(vIndex);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		drawTabItemBorderAndSetTitle();
		getZircoToIDGardAPI().updateBrowserUI();
	}

	class TabItem {

		String title;
		ImageView iv_thumb;
		TextView tvTitle;

		public String getTitle() {
			return title;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public ImageView getIv_thumb() {
			return iv_thumb;
		}

		public void setIv_thumb(ImageView iv_thumb) {
			this.iv_thumb = iv_thumb;
		}

		public TextView getTvTitle() {
			return tvTitle;
		}

		public void setTvTitle(TextView tvTitle) {
			this.tvTitle = tvTitle;
		}

	}

}
